<template>
    <div class="kt-password-strength">
        <div class="kt-password-strength-bar" :class="`kt-password-strength-level-${level}`"></div>
    </div>
</template>

<script lang="ts" setup>
import { ref, watch } from 'vue'

const props = defineProps({
    modelValue: {
        type: String,
        default: ''
    }
})

const level = ref(0)

watch(() => props.modelValue, (val) => {
    strength(val)
})

const strength = (v: any) => {
    let num = 1;
    //长度
    const has_length = v.length >= 6
    //包含数字
    const has_number = /\d/.test(v)
    //包含小写英文
    const has_lowercase = /[a-z]/.test(v)
    //包含大写英文
    const has_uppercase = /[A-Z]/.test(v)
    //没有连续的字符3位
    const no_continuity = !/(\w)\1{2}/.test(v)
    //包含特殊字符
    const has_special = /[`~!@#$%^&*()_+<>?:"{},./;'[\]]/.test(v)

    if (v.length <= 0 || !has_length) {
        level.value = 0;
        return false
    }
    if (has_number) {
        num += 1
    }
    if (has_lowercase) {
        num += 1
    }
    if (has_uppercase) {
        num += 1
    }
    if (no_continuity) {
        num += 1
    }
    if (has_special) {
        num += 1
    }
    level.value = num
}
</script>

<style scoped>
.kt-password-strength {
    height: 5px;
    width: 100%;
    background: var(--el-color-info-light-5);
    border-radius: 5px;
    position: relative;
    margin: 10px 0;

}

.kt-password-strength-bar {
    position: absolute;
    height: inherit;
    width: 0;
    border-radius: inherit;
    transition: width .25s ease-in-out, background .1s;
    background: transparent;
}
.kt-password-strength:before {
    left: 20%;
}

.kt-password-strength:after {
    right: 20%;
}

.kt-password-strength:before,
.kt-password-strength:after {
    position: absolute;
    content: "";
    display: block;
    width: 20%;
    height: inherit;
    border: 5px solid var(--el-bg-color-overlay);
    border-top: 0;
    border-bottom: 0;
    z-index: 1;
    background-color: transparent;
    box-sizing: border-box;
}



.kt-password-strength-level-1 {
    width: 20%;
    background-color: var(--el-color-error);
}

.kt-password-strength-level-2 {
    width: 40%;
    background-color: var(--el-color-error);
}

.kt-password-strength-level-3 {
    width: 60%;
    background-color: var(--el-color-warning);
}

.kt-password-strength-level-4 {
    width: 80%;
    background-color: var(--el-color-success);
}

.kt-password-strength-level-5 {
    width: 100%;
    background-color: var(--el-color-success);
}
</style>
